package android.sdk;

import android.content.Context;
import android.dto.AccelerometerEvent;
import android.dto.DataTransferObject;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class SensorController implements SensorEventListener{

    private NetworkController network;
    private SensorManager sensorManager;
    private boolean eventRegistered;
	private SDKClientService service;
	private int rate;
	private float maxRange;
	private float resolution;
   

	public SensorController(SDKClientService sdkClientService, NetworkController network) {
		this.service = sdkClientService;
        this.network = network;
        rate = SensorManager.SENSOR_DELAY_GAME;
		sensorManager = (SensorManager) this.service.getSystemService(Context.SENSOR_SERVICE);
		resolution = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER).getResolution();
		maxRange = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER).getMaximumRange();
	}

	public void registerAccelerometerEvent() {
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), this.rate);
        eventRegistered = true;
	}


	public void unregisterAccelerometerEvent() {
		sensorManager.unregisterListener(this);
		eventRegistered = false;
	}
	
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			AccelerometerEvent e = new AccelerometerEvent();
			e.setDeviceId(this.service.getDeviceId());
			e.setType(DataTransferObject.ACCELEROMETER_EVENT);
			
			e.setX(event.values[0]);
			e.setY(event.values[1]);
			e.setZ(event.values[2]);
			e.setTimestamp(event.timestamp);
			e.setAccuracy(event.accuracy);
			e.setMaxRange(this.maxRange);
			e.setResolution(this.resolution);
			
			network.sendObject(e);
		}
	}
	
	public void onResume() {
		if (eventRegistered)
			sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), this.rate);
	}
	
	public void onPause() {
		if (eventRegistered)
			sensorManager.unregisterListener(this);
	}

	public void setAccelerometerRate(int rate) {
		this.rate = rate;
		if(eventRegistered){
			sensorManager.unregisterListener(this);
			sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), rate);
		}
	}
	
}
